
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zfth/api/AlarmApi.dart';
import 'package:zfth/api/ReportApi.dart';
import 'package:flutter_echarts/flutter_echarts.dart';
import '../../components/form/LFormLogic.dart';
import '../../components/form/LFormPage.dart';
import '../../components/list/LCellListLogic.dart';
import '../../utils/Settings.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import '../../utils/StoreData.dart';



class StateChangePage extends StatefulWidget{
  const StateChangePage({super.key});

  @override
  State<StateChangePage> createState() =>StateChangeState();

}

class StateChangeState extends State<StateChangePage> with AutomaticKeepAliveClientMixin{
  String formTag = "TrendAlarmHandleDetail";
  late final LFormLogic lFormLogic;
  bool keepAlive = true;
  List formItems = [
    {"field":'deviceNo',"label":'采集终端',"component":'select',"readonly":false,"required":true,"isShowLabel":true,"dictCode":Settings.dictCodes["温湿度设备"]},
    {"field":'startDate',"label":'开始时间',"component":'date',"readonly":false,"required":true,"isShowLabel":true},
    {"field":'endDate',"label":'结束时间',"component":'date',"readonly":false,"required":true,"isShowLabel":true},
  ];
  Map formData={};

  List wendu = [];
  List shidu = [];
  List xAxisData = [];





  @override
  void initState() {
    lFormLogic = Get.put(LFormLogic(),tag:formTag);
    lFormLogic.init(formItems: formItems, formData: formData,tag: formTag,onChangeCallback: onChange);
    super.initState();
  }





  @override
  void dispose() {
    Get.delete<LFormLogic>(tag: formTag);
    super.dispose();
  }

  @override
  bool get wantKeepAlive => keepAlive;
  bool isShowButton = true;

  ///内容改变后的回调
  void onChange(re){}



  ///查询温湿度变化
  void queryTHByDeviceNo() async{
    if((lFormLogic.getFormKey().currentState as FormState).validate()){
      Map<String,dynamic> param = {"deviceNo":formData["deviceNo"],"startDate":formData["startDate"],"endDate":formData["endDate"]};
      dynamic res =  await ReportApi.queryTHByDeviceNo(param);
      if(res["success"]){
        List result = res["result"];
        for(dynamic item in result){
          wendu.add(item["deviceTemperature"]);
          shidu.add(item["deviceHumidity"]);
          xAxisData.add(item["createTime"]);
        }
        setState(() {});
      }else{
        EasyLoading.showError("数据查询失败");
      }
    }

    }


  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
        backgroundColor: Settings.backgroundColor,
        appBar: AppBar(
          title: const Text("趋势报警处理"),
          centerTitle: true,
          elevation: 0,
        ),
        body: SingleChildScrollView(
          child: Stack(
            children: [
              Column(
                children: [
                  LFormPage(tag:formTag),
                  Padding(
                      padding: const EdgeInsets.all(10),
                      child: Row(
                        children: [
                          Expanded(
                            child: Visibility(
                              visible: isShowButton,
                              child: SizedBox(
                                height: 50,
                                child: OutlinedButton(
                                  style: ButtonStyle(
                                    backgroundColor: MaterialStateProperty.resolveWith<Color>((states) {
                                      return Settings.primaryColor;
                                    }),
                                    foregroundColor: MaterialStateProperty.resolveWith<Color>((states) {
                                      return Colors.white;
                                    }),
                                  ),
                                  onPressed:queryTHByDeviceNo,
                                  child: const Text('查询',style: TextStyle(fontSize: 17,)),

                                ),
                              ),
                            ),
                          )
                        ],
                      )
                  ),
                  Card(
                    elevation: 0.2,
                    margin: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                    child: SizedBox(
                        width: MediaQuery.of(context).size.width-20,
                        height: 220,
                        child: Echarts(
                            option:'''
                           {
                              tooltip: {
                                trigger: 'axis'
                              },
                              legend: {
                                data: ['温度','湿度']
                              },
                              grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true
                              },
                              xAxis: {
                                type: 'category',
                                boundaryGap: false,
                                data: ${jsonEncode(xAxisData)}
                              },
                              yAxis: [
                                {
                                  type: 'value',
                                  name:'温度',
                                  axisLabel: { formatter: '{value} °C' }
                                },
                                {
                                  type: 'value',
                                  name:'湿度',
                                  axisLabel: { formatter: '{value} %' },
                                  axisLine: {
                                    show: false
                                  },
                                  splitLine: {
                                    show: false
                                  }
                                
                                }
                              ],
                              dataZoom: [{
                                height:30,
                                type: 'slider', 
                                start: 0,      
                                end: 100, 
                                show:true,
                                bottom:0
                              }],
                              series: [
                                {
                                  name: '温度',
                                  type: 'line',
                                  data: ${jsonEncode(wendu)}
                                },
                                {name:'湿度',data:${jsonEncode(shidu)},type:'line',yAxisIndex:'1',}
                              ]
                            }
                          
                          '''
                        )
                    ),
                  )
                ],
              ),
            ],
          ),
        )




    );
  }


}